<template>
    <section class="todoapp">
        <TodoHeader @add="addFn" :arr="showList"></TodoHeader>
        <TodoMain :arr="showList" @del="delFn"></TodoMain>
        <TodoFooter
            :arr="list"
            @changeType="changeTypeFn"
            @clearDone="clearDoneFn"
        ></TodoFooter>
    </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

import './styles/base.css'
import './styles/index.css'

export default {
    data() {
        return {
            type: 'all',
            list: JSON.parse(localStorage.getItem('todos25')) || [],
        }
    },
    // 侦听 本地存储
    watch: {
        list: {
            deep: true,
            handler() {
                localStorage.setItem('todos25', JSON.stringify(this.list))
            },
        },
    },
    computed: {
        // 底部高亮控制
        showList() {
            if (this.type === 'active') {
                // 未完成的高亮
                return this.list.filter((item) => !item.isDone)
            } else if (this.type === 'complete') {
                // 已完成的高亮
                return this.list.filter((item) => item.isDone)
            } else {
                // 全部
                return this.list
            }
        },
    },
    methods: {
        // 控制高亮显示
        changeTypeFn(type) {
            this.type = type
        },
        // 删除已完成的
        clearDoneFn() {
            this.list = this.list.filter((item) => !item.isDone)
        },
        // 删除
        delFn(id) {
            // 过滤 得出新数组 重新赋值
            this.list = this.list.filter((item) => item.id !== id)
        },
        // 添加任务
        addFn(name) {
            this.list.unshift({
                id: +new Date(),
                name,
                isDone: false,
            })
        },
    },
    components: {
        // 组件名: 组件对象
        TodoHeader,
        TodoMain,
        TodoFooter,
    },
}
</script>
